package com.xhtt.modules.photo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.modules.photo.dao.PhotoCustomerMapper;
import com.xhtt.modules.photo.entity.PhotoCustomer;
import com.xhtt.modules.photo.entity.PhotoProduct;
import com.xhtt.modules.photo.entity.PhotoStage;
import com.xhtt.modules.photo.service.IPhotoCustomerService;
import com.xhtt.modules.photo.service.IPhotoProductService;
import com.xhtt.modules.photo.service.IPhotoStageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 现场拍照客户列表 服务实现类
 * </p>
 *
 * @author xj
 * @since 2019-02-14
 */
@Service
public class PhotoCustomerServiceImpl extends ServiceImpl<PhotoCustomerMapper, PhotoCustomer> implements IPhotoCustomerService {

    @Autowired
    private IPhotoProductService photoProductService;

    @Autowired
    private IPhotoStageService photoStageService;

    @Override
    public List<PhotoCustomer> queryList(String name) {
        return baseMapper.selectList(new LambdaQueryWrapper<PhotoCustomer>()
                .like(name != null && !name.equals(""), PhotoCustomer::getName, name));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {

        // TODO 暂定 可能涉及业务逻辑

        // 删除客户表
        baseMapper.deleteById(id);

        // 查询产品表

        List<PhotoProduct> photoProducts = photoProductService
                .list(new LambdaQueryWrapper<PhotoProduct>().eq(PhotoProduct::getCustomerId, id));

        // 获取产品关联的装车台号
        List<Integer> productIds = photoProducts.stream().map(PhotoProduct::getId).collect(Collectors.toList());

        // 删除产品表
        photoProductService.remove(new LambdaQueryWrapper<PhotoProduct>().eq(PhotoProduct::getCustomerId, id));

        // 删除装车台表
        photoStageService.remove(new LambdaQueryWrapper<PhotoStage>().in(PhotoStage::getProductId, productIds));
    }

    @Override
    public List<PhotoCustomer> queryListByName(String name) {

        return baseMapper.selectList(new LambdaQueryWrapper<PhotoCustomer>().like(PhotoCustomer::getName, name));
    }
}
